<!-- 首页 -->
<template>
  <el-card>
    <div>
      <!-- 按钮添加 -->
      <el-button type="primary" size="default" @click="addBrand" icon="Plus">
        添加品牌
      </el-button>
      <!-- 表格组件 -->
      <el-table border stripe :data="trademarkArr" v-loading="loading">
        <el-table-column
          prop="id"
          label="序号"
          width="80px"
          align="center"
          type="index"
        ></el-table-column>
        <el-table-column prop="tmName" label="品牌名称"></el-table-column>
        <el-table-column prop="logoUrl" label="品牌LOGO">
          <template #default="scope">
            <img :src="scope.row.logoUrl" style="width: 100px" />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #="{ row, column, $index }">
            <el-button
              type="warning"
              size="small"
              icon="Edit"
              @click="updataTrademark(row)"
            ></el-button>

            <el-popconfirm title="确定删除吗?" @confirm="onDelete(row)">
              <template #reference>
                <el-button type="danger" size="small" icon="Delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器组件 -->
      <el-pagination
        background
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 30]"
        layout="  prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <!-- 对话框组件 添加与修改 -->
      <el-dialog v-model="dialogTableVisible" :title="dialogTitle">
        <el-form
          ref="formRef"
          style="width: 80%"
          :model="trademarkParams"
          :rules="rules"
        >
          <el-form-item label="品牌名称" prop="tmName">
            <el-input
              placeholder="请您输入品牌名称"
              v-model="trademarkParams.tmName"
            />
          </el-form-item>
          <el-form-item label="品牌LOGO" prop="logoUrl">
            <!-- upload组件属性:action图片上传路径书写/api,代理服务器不发送这次post请求  -->
            <el-upload
              class="avatar-uploader"
              action="/api/admin/product/fileUpload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="trademarkParams.logoUrl"
                :src="trademarkParams.logoUrl"
                class="avatar"
              />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <!-- 具名插槽:footer -->
        <template #footer>
          <el-button type="primary" size="default" @click="cancel">
            取消
          </el-button>
          <el-button type="primary" size="default" @click="confirm">
            确定
          </el-button>
        </template>
      </el-dialog>
    </div>
  </el-card>
</template>
<script setup lang="ts">
import { ElMessage, UploadProps } from 'element-plus'
import { ref, onMounted, reactive, nextTick } from 'vue'
import {
  reqHasTrademark,
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
} from '@/api/product/trademark/index'
import type {
  Records,
  TradeMarkResponseData,
  TradeMark,
} from '@/api/product/trademark/type'
// import { useuserStore } from '@/store/modules/user'
// const userStore = useuserStore()
//品牌自定义校验规则方法
const validatorTmName = (rule: any, value: any, callBack: any) => {
  //是当表单元素触发blur时候,会触发此方法
  //自定义校验规则
  if (value.trim().length >= 2) {
    callBack()
  } else {
    //校验未通过返回的错误的提示信息
    callBack(new Error('品牌名称位数大于等于两位'))
  }
}
//品牌LOGO图片的自定义校验规则方法
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  //如果图片上传
  if (value) {
    callBack()
  } else {
    callBack(new Error('LOGO图片务必上传'))
  }
}

//表单校验规则对象
const rules = {
  tmName: [
    //required:这个字段务必校验,表单项前面出来五角星
    //trigger:代表触发校验规则时机[blur、change]
    { required: true, trigger: 'blur', validator: validatorTmName },
  ],
  logoUrl: [{ required: true, validator: validatorLogoUrl }],
}
//上传图片组件->上传图片之前触发的钩子函数
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  //钩子是在图片上传成功之前触发,上传文件之前可以约束文件类型与大小
  //要求:上传文件格式png|jpg|gif 4M
  // console.log(rawFile, 22222)

  if (
    rawFile.type == 'image/png' ||
    rawFile.type == 'image/jpeg' ||
    rawFile.type == 'image/gif'
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件大小小于4M',
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件格式务必PNG|JPG|GIF',
    })
    return false
  }
}
//图片上传成功钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile,
) => {
  if (response.code !== 200) return ElMessage.error('图片上传失败!')

  //response:即为当前这次上传图片post请求服务器返回的数据
  //收集上传图片的地址,添加一个新的品牌的时候带给服务器
  trademarkParams.logoUrl = response.data
  //图片上传成功,清除掉对应图片校验结果
  formRef.value.clearValidate('logoUrl')
}
// 获取表单组件实例
const formRef = ref()
const dialogTitle = ref<string>('添加品牌')
// 打开对话框
const dialogTableVisible = ref(false)
// loading开启
const loading = ref(true)
//存储已有品牌的数据
const trademarkArr = ref<Records>([])
// 当前页码
const pageNo = ref<number>(1)
// 每页显示的个数
const pageSize = ref<number>(5)
// 总条数
const total = ref(0)
// 加载时执行
onMounted(() => {
  getTrademarkData()
})
//定义收集新增品牌数据
let trademarkParams = reactive<TradeMark>({
  tmName: '',
  logoUrl: '',
})
// 获取品牌信息
const getTrademarkData = async () => {
  // 开启loading
  loading.value = true
  const res: TradeMarkResponseData = await reqHasTrademark(
    pageNo.value,
    pageSize.value,
  )
  // 关闭loading
  loading.value = false
  // console.log(res)
  if (res.code !== 200) return ElMessage.error(res.message)
  total.value = res.data.total
  trademarkArr.value = res.data.records
}
// 点击添加品牌
const addBrand = () => {
  dialogTitle.value = '添加品牌'
  dialogTableVisible.value = true
  //清空收集数据
  trademarkParams.id = 0
  trademarkParams.tmName = ''
  trademarkParams.logoUrl = ''
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
}
// 点击修改品牌
const updataTrademark = (row: any) => {
  dialogTitle.value = '修改品牌'
  dialogTableVisible.value = true
  // console.log(row, 123123)
  trademarkParams.tmName = row.tmName
  trademarkParams.logoUrl = row.logoUrl
  trademarkParams.id = row.id
}
// 点击删除品牌
const onDelete = async (row: any) => {
  const res = await reqDeleteTrademark(row.id)
  if (res.code == 200) {
    getTrademarkData()
    //弹出提示信息
    ElMessage({
      type: 'success',
      message: res.message,
    })
  } else {
    getTrademarkData()
    //弹出提示信息
    ElMessage({
      type: 'warning',
      message: res.data,
    })
  }
}
// 当前页码发生变化时触发
const handleCurrentChange = () => {
  console.log(pageNo.value, pageSize.value)
  getTrademarkData()
}
// 每页条数发生变化时触发
const handleSizeChange = () => {
  console.log(pageNo.value, pageSize.value)
  getTrademarkData()
}
//对话框底部取消按钮
const cancel = () => {
  // 清空表单数据
  formRef.value.resetFields()
  //对话框隐藏
  dialogTableVisible.value = false
}
const confirm = async () => {
  //在你发请求之前,要对于整个表单进行校验
  //调用这个方法进行全部表单相校验,如果校验全部通过，在执行后面的语法
  await formRef.value.validate()
  let result: any = await reqAddOrUpdateTrademark(trademarkParams)
  //添加|修改已有品牌
  if (result.code == 200) {
    //关闭对话框
    dialogTableVisible.value = false
    // 清空表单数据
    formRef.value.resetFields()
    //弹出提示信息
    ElMessage({
      type: 'success',
      message: trademarkParams.id ? '修改品牌成功' : '添加品牌成功',
    })
    //再次发请求获取已有全部的品牌数据
    getTrademarkData()
  } else {
    //添加品牌失败
    ElMessage({
      type: 'error',
      message: trademarkParams.id ? '修改品牌失败' : '添加品牌失败',
    })
    //关闭对话框
    dialogTableVisible.value = false
    // 清空表单数据
    formRef.value.resetFields()
  }
}
</script>
<script lang="ts">
export default {
  name: 'Setting',
}
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
